﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using PMIS.Shared.DTO;
using PMIS.Shared.Models;
using PMIS.WebApi.Model;
using PMIS.WebApi.Services;
using PMIS.WebApi.SnowflakeId;
using PMIS.WebApi.Common.Attributes;
using System.Linq.Expressions;
 
namespace PMIS.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class DeptController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IDeptService _service;
        private readonly SnowflakeIdGenerator _idGenerator;

        public DeptController(IDeptService service, IMapper mapper, SnowflakeIdGenerator idGenerator)
        {
            _service = service;
            _mapper = mapper;
            _idGenerator = idGenerator;
        }

        [HttpPost]
        public async Task<IActionResult> Add(DepartmentDto d)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var dept = _mapper.Map<Department>(d);
            dept.Id = _idGenerator.GetId();
            var data = await _service.AddEntityAsync(dept);
            var res = new ApiResult() { data = data };
            return Ok(res);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(List<string> ids)
        {
            var data = await _service.DeleteEntityAsync<Department>(x => ids.Contains(x.Id));
            var res = new ApiResult() { data = data };
            return Ok(res);
        }

        [HttpGet]
        public async Task<IActionResult> Get(string id)
        {
            var data = await _service.GetEntityAsync(id);
            var res = new ApiResult() { data = data };
            return Ok(res);
        }

        [HttpPut]
        public async Task<IActionResult> Update(DepartmentDto d)
        {
            var dept = _mapper.Map<Department>(d);
            var data = await _service.UpdateEntityAsync(dept);
            var res = new ApiResult() { data = data };
            return Ok(res);
        }

        [HttpGet]
        public async Task<IActionResult> GetList(int? pageNum, int? pageSize, string? name)
        {
            Expression<Func<Department, bool>>? expression = null;
            if (!string.IsNullOrEmpty(name))
            {
                expression = p => p.Name.Contains(name);
            }
            var data = await _service.GetEntityListAsync(pageNum, pageSize, expression);
            var res = new ApiResult() { data = data };
            return Ok(res);
        }
    }
}
